package com.iwechat.adapter.mina.entity;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;

public class PDUHeader implements PDU {

    protected int      pkgLen;
    protected int      command;
    protected int      sequence;
    protected long     timestamp;
    private static int num = 0;

    /**
     * Constructors
     *
     *
     * @param createSelf
     *            true 值由构造器构建 false值由setter设置
     */
    public PDUHeader(boolean createSelf) {
        if (createSelf) {
            this.pkgLen = PDU.HEAD_LEN;
            this.sequence = getSeqNum();
            this.timestamp = System.currentTimeMillis();
        }
    }

    public PDUHeader() {
    }

    /**
     * 获取消息序号
     *
     *
     * @return
     */
    public synchronized static int getSeqNum() {
        num++;
        num = num % Integer.MAX_VALUE;
        return num;
    }

    @Override
    public IoBuffer toIoBuffer(Charset charset) throws Exception {
        IoBuffer buffer = IoBuffer.allocate(HEAD_LEN);
        buffer.putInt(pkgLen);
        buffer.putInt(command);
        buffer.putInt(sequence);
        buffer.putLong(timestamp);
        buffer.flip();
        return buffer;
    }

    public void setPkgLen(int pkgLen) {
        this.pkgLen = pkgLen;
    }

    public void setCommand(int command) {
        this.command = command;
    }

    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public int getCommand() {
        return command;
    }

    public int getPkgLen() {
        return pkgLen;
    }

    public int getSequence() {
        return sequence;
    }

    public long getTimestamp() {
        return timestamp;
    }
}
